//
//  BQHomeTableViewController.m
//  BeeQuick
//
//  Created by Asun on 2017/7/9.
//  Copyright © 2017年 BecomeRich. All rights reserved.
//



#import  "BQHomeTableViewController.h"
#import  "BQFocus.h"
#import  "BQIcons.h"
#import  "BQActivites.h"
#import  "BQCustomButton.h"
#import  "BQProductModel.h"
#import  "BQAccountManager.h"
#import  "UIColor+MLAddition.h"
#import  "BQCycleWebController.h"
#import  "BQIconsWebViewController.h"
#import  "BQActivitesWebViewController.h"
#import  "BQShopTableViewCell.h"
#import  "NSAttributedString+Additon.h"
#import  "BQMapViewController.h"
#import  "BQScanningViewController.h"
#import   <MJRefresh/MJRefresh.h>
#import "BQSearchViewController.h"
#import "BQDetailViewController.h"

@interface BQHomeTableViewController ()<SDCycleScrollViewDelegate,UIGestureRecognizerDelegate,CAAnimationDelegate>

@property (strong, nonatomic)NSMutableArray  *          imgArray;

@property (strong, nonatomic)NSArray<BQFocus *>         *focusModelArray;

@property (strong, nonatomic)NSArray<BQActivites *>     *activitesArray;

@property (strong, nonatomic)NSArray<BQProductModel *>  *shopArray;

@end

@implementation BQHomeTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //实例化
    
    [self loadData];
    
    self.imgArray = [NSMutableArray array];
    
    self.focusModelArray = [NSArray array];
    
    self.iconsModelArray = [NSArray array];
    
    self.activitesArray = [NSArray array];
    
    self.shopArray = [NSArray array];
    
    [self setupNavigationView];
    
    [self registerNotification];
    
    [self setupBarButton];
    
    [self setupulling];
    
    [self setupRefresh];
    
    [self.tableView registerClass:[BQShopTableViewCell class] forCellReuseIdentifier:@"BQShopTableViewCell"];
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"buyID"];
    
    self.tableView.backgroundColor = [UIColor lightGrayColor];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [self.navigationController.navigationBar setBackgroundImage: [UIImage imageNamed:@"v2_coupon_verify_normal"]
                             forBarMetrics:UIBarMetricsDefault];

}

- (void)setupNavigationView {
    
    BQCustomButton* navButton = [[BQCustomButton alloc]initWithFrame:CGRectMake(0, 0, 100, 50)];
    
    navButton.titleLabel.font = [UIFont systemFontOfSize:13];
    
    [navButton setTitle:@"在地图中定位" forState:UIControlStateNormal];
    
    [navButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    [navButton setImage:[UIImage imageNamed:@"icon_mapmarker_cir"] forState:UIControlStateNormal];
    
    [navButton addTarget:self action:@selector(pushMapController) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.titleView = navButton;
}

#pragma mark - nav按钮设置
- (void)setupBarButton{
    
    UIButton *leftButton = [self setupButtonItemWithImageName:@"icon_black_scancode" andTitle:@"扫一扫"];
    
    [leftButton addTarget:self action:@selector(scnicon) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    
    UIButton *rightButton = [self setupButtonItemWithImageName:@"icon_search" andTitle:@"搜索"];
    [rightButton addTarget:self action:@selector(search) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
}

- (void)registerNotification{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickIncreaseButton:) name:ToValueNotificationName object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(push:) name:ToPushNotificationName object:nil];
}

#pragma mark - Push界面
- (void)push:(NSNotification *)noti{
    
    BQDetailViewController *detail = [[BQDetailViewController alloc]init];
    
    detail.model = noti.object;
    
    [self.navigationController pushViewController:detail animated:YES];
}

- (void)pushMapController{
    
    BQMapViewController *map = [[BQMapViewController alloc]init];
    
    [self.navigationController pushViewController:map animated:YES];
}


- (void)scnicon{
    
    BQScanningViewController *scan = [[BQScanningViewController alloc]init];
    
    [self.navigationController pushViewController:scan animated:YES];
    
}


- (void)search{
    
    BQSearchViewController *search = [[BQSearchViewController alloc]init];
    
    [self.navigationController pushViewController:search animated:YES];
}

#pragma mark - 下拉刷新
- (void)setupulling{
    
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(endpulling)];
    
    UIImage *image1 = [UIImage imageNamed:@"v2_pullRefresh1"];
    
    UIImage *image2 = [UIImage imageNamed:@"v2_pullRefresh2"];
    
    NSArray *pullArray = @[image1,image2];
    
    [header setImages:pullArray duration:1 forState:MJRefreshStateIdle];
    
    
    [header setImages:pullArray duration:1 forState:MJRefreshStatePulling];
    
    [header setImages:pullArray duration:1 forState:MJRefreshStateRefreshing];
    
    header.lastUpdatedTimeLabel.hidden = YES;
    
    self.tableView.mj_header = header;
    
}

- (void)endpulling{
    
    [self.tableView.mj_header endRefreshing];
}

- (void)setupRefresh{
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(endRefreshing)];
}

- (void)endRefreshing{
    
    [self.tableView.mj_footer endRefreshing];
}

#pragma mark - 动画
- (void)clickIncreaseButton: (NSNotification *)noti{
    
    BQProductModel *model = noti.object;
    
    NSInteger num = [noti.userInfo[@"num"]  intValue];
    
    if (num == 1) {
        
        CGPoint startPoint = [noti.userInfo[@"point"] CGPointValue];
        
        CGPoint controlPoint = CGPointMake(startPoint.x + 100, startPoint.y - 100);
        
        CGPoint endPoint = CGPointMake(_ScreenWidth / 4 * 2.5, _ScreenHeight - 44);
        
        UIImageView *imgIcon = [[UIImageView alloc] init];
        
        NSURL *imgUrl = [[NSURL alloc] initWithString:model.img];
        
        imgIcon.frame = CGRectMake(startPoint.x, startPoint.y, 185, 150);
        
        [imgIcon sd_setImageWithURL:imgUrl placeholderImage:[UIImage imageNamed:@"v2_placeholder_full_size"]];
        
        imgIcon.layer.masksToBounds = YES;
        
        [kWindow addSubview:imgIcon];
        
        UIBezierPath *bezierPath = [UIBezierPath bezierPath];
        
        [bezierPath moveToPoint:startPoint];
        [bezierPath addQuadCurveToPoint:endPoint controlPoint:controlPoint];
        
        // 关键帧动画
        CAKeyframeAnimation *keyFrame = [CAKeyframeAnimation animationWithKeyPath:@"position"];
        
        // 设置路径
        keyFrame.path = bezierPath.CGPath;
        
        // 设置动画时间
        keyFrame.duration = 1;
        
        // 保持动画的最新状态
        keyFrame.removedOnCompletion = NO;
        keyFrame.fillMode = kCAFillModeBoth;
        
        keyFrame.delegate = self;
        
        [keyFrame setValue:imgIcon forKey:@"imgIcon"];
        
        CABasicAnimation *basic = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        
        basic.toValue = @0.5;
        
        basic.duration = 1;
        
        [imgIcon.layer addAnimation:basic forKey:nil];
        [imgIcon.layer addAnimation:keyFrame forKey:nil];
    }
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//  MARK:动画代理方法 动画执行完 自动回调
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    
    UIImageView *imgIcon = [anim valueForKey:@"imgIcon"];
    
    [imgIcon removeFromSuperview];
}

//自定义按钮
- (UIButton *)setupButtonItemWithImageName:(NSString *)imageName andTitle:(NSString *)title
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    
    button.frame = CGRectMake(0, 0, 54, 30);
    
    NSAttributedString *attr = [NSAttributedString imageTextWithImage:[UIImage imageNamed:imageName] imageWH:20 title:title fontSize:12 titleColor:[UIColor darkGrayColor] spacing:3];
    
    [button setAttributedTitle:attr forState:UIControlStateNormal];
    
    button.titleLabel.numberOfLines = 0;
    button.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    return button;
}

#pragma mark - 获取数据 -

- (void)setupUI{
    //组头
    UIView  *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 800)];
    
    headerView.backgroundColor = [UIColor whiteColor];
    
    self.tableView.tableHeaderView = headerView;
   //轮播器
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, headerView.frame.size.width, 150) delegate:self placeholderImage:[UIImage imageNamed:@"v2_placeholder_full_size"]];
    
    cycleScrollView.imageURLStringsGroup = self.imgArray;
    
    [headerView addSubview:cycleScrollView];
    
    UIView* buttonView = [[UIView alloc]initWithFrame:CGRectMake(0, 150, headerView.frame.size.width, 120)];
    
    [headerView addSubview:buttonView];
    //按钮
    for (int i=0; i<_iconsModelArray.count; i++ ) {
        
        UIImageView* buttonImage = [[UIImageView alloc]initWithFrame:CGRectMake(i*headerView.frame.size.width/4, 20, headerView.frame.size.width/4, 50)];
        
        BQIcons *iconsModel = self.iconsModelArray[i];
        
        [buttonImage sd_setImageWithURL:[NSURL URLWithString:iconsModel.img]];
        
        [buttonView addSubview:buttonImage];
        
        UILabel * buttonLabel = [[UILabel alloc]initWithFrame:CGRectMake(i*headerView.frame.size.width/4, 70, headerView.frame.size.width/4, 20)];
        
        buttonLabel.textAlignment = NSTextAlignmentCenter;
        
        buttonLabel.text = iconsModel.name;
        
        [buttonView addSubview:buttonLabel];
        
        buttonImage.tag = i;
        
        buttonImage.userInteractionEnabled = YES;
        
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(actionButton:)];
        
        [buttonImage addGestureRecognizer:tap];
    }
    
    //大图
    UIView *activitces = [[UIView alloc]initWithFrame:CGRectMake(0, 250, headerView.frame.size.width, 500)];
    
    [headerView addSubview:activitces];
    
    for (int i = 0; i<self.activitesArray.count; i++) {
        
        UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 50+i*130, headerView.frame.size.width-20, 120)];
        
        BQActivites *activitesModel = self.activitesArray[i];
        
        imageView.tag = i;
        
        imageView.userInteractionEnabled = YES;
        
        [imageView sd_setImageWithURL:[NSURL URLWithString:activitesModel.img]];
        
        [activitces addSubview:imageView];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(actionImageView:)];
        
        [imageView addGestureRecognizer:tap];
    }
}

//点击按钮
- (void)actionButton: (UIGestureRecognizer  *)tap{
    
    BQIconsWebViewController *iconsController = [[BQIconsWebViewController alloc]init];
    
    NSInteger index = tap.view.tag;
    
    BQIcons  *iconsModel = self.iconsModelArray[index];
    
    iconsController.urlStr = iconsModel.customURL ;
    
    [self.navigationController pushViewController:iconsController animated:YES];
}

//点击大图事件
- (void)actionImageView: (UIGestureRecognizer  *)tap{
    
    BQActivitesWebViewController *activitesController = [[BQActivitesWebViewController alloc]init];
    
    NSInteger index = tap.view.tag;
    
    BQActivites  *activites = self.activitesArray[index];
    
    activitesController.urlStr = activites.customURL;
    
    [self.navigationController pushViewController:activitesController animated:YES];
}

#pragma mark - SDCycleScrollViewDelegate 点击跳转 -
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    
    BQCycleWebController* cycleWebController = [BQCycleWebController new];
    
    BQFocus* focusModel = self.focusModelArray[index];
    
    cycleWebController.urlStr = focusModel.toURL;
    
    [self.navigationController pushViewController:cycleWebController animated:NO];
}

#pragma mark -  UITableViewDateSource -
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return  2;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return  1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"buyID"forIndexPath:indexPath];
        
        cell.textLabel.text = @"新鲜热卖";
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
    
    BQShopTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BQShopTableViewCell" forIndexPath:indexPath];
    
    cell.shopModelAry = self.shopArray;
    
    return cell;
}

#pragma mark - cell间距
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

#pragma mark - 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 20;
    }
    return self.shopArray.count%2>0 ? (self.shopArray.count/2+1) * 250: (self.shopArray.count/2) * 250;
}

- (void)loadData{
    
    NSMutableDictionary *dict = [self setValue:@"1" andKey:@"call"];
    
    NSMutableDictionary *shop = [self setValue:@"2" andKey:@"call"];
    
#pragma mark - 头部视图数据
    [[BQAccountManager sharedInstance] POSTWithUrlString:focus_url parameters:dict success:^(id responseObject) {
        
        NSDictionary *data = responseObject[@"data"];
        
        //大图数组
        NSArray *activitiesArray = data[@"activities"];
        
        //图标数组
        NSArray *iconsArray = data[@"icons"];
        
        //轮播器数组
        NSArray *focusArray = data[@"focus"];
        
        NSMutableArray *imgArrM = [NSMutableArray array];
        
        for (NSDictionary *dict in focusArray)
        {
            NSString *urlStr = dict[@"img"];
            
            [imgArrM addObject:urlStr];
        }
        
        self.imgArray = imgArrM;
        
        //轮播器模型数组
        self.focusModelArray = [NSArray yy_modelArrayWithClass:[BQFocus class] json:focusArray];
        
        //按钮模型数组
        self.iconsModelArray = [NSArray yy_modelArrayWithClass:[BQIcons class] json:iconsArray];
        
        //大图模型数组
        self.activitesArray = [NSArray yy_modelArrayWithClass:[BQActivites class] json:activitiesArray];
        
        //回到主线程刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            [self setupUI];
            
            [self.tableView reloadData];
            
        });
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
#pragma mark - 请求商品列表数据 -
    
//    [[BQAccountManager sharedInstance] POSTWithUrlString:shop_url parameters:shop success:^(id responseObject) {
//        
//        self.shopArray = [NSArray yy_modelArrayWithClass:[BQProductModel class] json:responseObject[@"data"]];
//        
//    } failure:^(NSError *error) {
//        
//        NSLog(@"%@",error);
//        
//    }];
    
    [[BQAccountManager sharedInstance] loadFreshProductsWithSuccessBlock:^{
        self.shopArray = [BQAccountManager sharedInstance].freshProducts;
        
    } andFailureBlock:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

- (NSMutableDictionary *)setValue:(NSString *)value andKey: (NSString *)key{
    
    NSMutableDictionary * dict = [NSMutableDictionary new];
    
    [dict setValue:value forKey:key];
    
    return dict;
}

@end
